import styles from './pwd.module.less'
import Modal from '@/components/modal'
import Button from '@/components/button'
import cm from 'classnames'
import Input from '@/components/input'
import { validPwd, surePwd, handleLocalUserInfo } from '@/utils/utils'
import { forgetPwd } from '@/api/user'
import { pick } from 'lodash-es'
import { cncryptionCipher } from '@/utils/encode'
import Toast from '@/components/toast'
import { useRef, useEffect } from 'react'
const Index = (props) => {
  const submitRef = useRef()
  const { visible, close, formInfo, setFormInfo } = props
  const { clearUserToken } = handleLocalUserInfo()
  const onSubmit = async () => {
    const isValidPwd = validPwd(formInfo.password)
    const isSurePwd = surePwd(formInfo.repwd)
    setFormInfo({
      pwdErr: !isValidPwd,
      repwdErr: !formInfo.repwd,
    })
    if (!isValidPwd || !isSurePwd) {
      return
    }
    const res = await forgetPwd({ password: cncryptionCipher(formInfo.password), ...pick(formInfo, ['email', 'code']) })

    if (!res.code) {
      clearUserToken()
      Toast.normal('密码修改成功，请登录')
      setTimeout(() => {
        close()
      }, 1500)
    }
  }

  useEffect(() => {
    const down = (e) => {
      if (e.keyCode === 13) {
        submitRef.current.click()
      }
    }
    window.addEventListener('keydown', down)
    return () => {
      window.removeEventListener('keydown', down)
    }
  }, [])

  return (
    <Modal visible={visible}>
      <div className={styles.pwd}>
        <h1 className={styles.title}>修改密码</h1>
        <img src="/images/close.webp" className={styles.close} onClick={close} />
        <p className={styles.inputLabel}>
          <span>新密码</span>
          {formInfo.pwdErr && <span>密码不符合要求，请重新输入</span>}
        </p>
        <p className={cm(styles.inputLabel, styles.inputTip)}>须是6-20个英文字母、数字，且以上两种必须都包含</p>
        <Input
          inputClass="input"
          id="pwd"
          placeholder="请输入新密码"
          onChange={(e) => setFormInfo({ password: e.target.value })}
          hasSuffix
        />
        <p className={styles.inputLabel}>
          <span>确认新密码</span>
          {formInfo.repwdErr && <span>两次密码不一致，请确认</span>}
        </p>
        <Input
          inputClass="input"
          id="pwdSecond"
          placeholder="请输入新密码"
          onChange={(e) => setFormInfo({ repwd: e.target.value })}
          hasSuffix
        />
        <Button onClick={onSubmit} ref={submitRef} className={styles.submit}>
          提交
        </Button>
      </div>
    </Modal>
  )
}

export default Index
